package com.shiguiwu.springboot3.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description: redis 服务
 * @author: stone
 * @date: Created by 2025/9/22 14:59
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springboot3.service
 */
@Service
public class RedisService {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    public void del(String key){
        redisTemplate.delete(key);
    }
    // Redis中管理refresh_token示例
    public void storeRefreshToken(String userId, String refreshToken, long expirationTime) {
        String key = "refresh_token:" + userId;
        redisTemplate.opsForValue().set(key, refreshToken, expirationTime, TimeUnit.MILLISECONDS);
    }

    public boolean isValidRefreshToken(String userId, String refreshToken) {
        return refreshToken.equals(getRefreshToken(userId));
    }


    public String getRefreshToken(String username) {
        String key = "refresh_token:" + username;
        return (String) redisTemplate.opsForValue().get(key);
    }

    public boolean delRefreshToken(String username) {
        String key = "refresh_token:" + username;
        return Boolean.TRUE.equals(redisTemplate.delete(key));
    }



    public void setValue(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public void setValue(String key, Object value,Long expirationTime,TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value,expirationTime, timeUnit);
    }

    public Object getValue(String key) {
        return redisTemplate.opsForValue().get(key);
    }


    public void setHashValue(String key,String hashKey, Object value) {
        redisTemplate.opsForHash().put(key,hashKey,value);
    }

    public Object getHashValue(String key,String hashKey) {
        return redisTemplate.opsForHash().get(key,hashKey);
    }


    public void delHashValue(String key,String hashKey) {
         redisTemplate.opsForHash().delete(key,hashKey);
    }

    public void expire(String key, long timeout, TimeUnit timeUnit) {
        redisTemplate.expire(key, timeout, timeUnit);
    }

    public Map<Object, Object> getHashEntries(String key) {
        return   redisTemplate.opsForHash().entries(key);
    }

}
